package homelesspartners.client.model;

import java.util.ArrayList;
import java.util.Iterator;

public class ShoppingList {

	public static final int MAX_NUMBER_OF_GIFTS = 100;

	private ArrayList gifts = new ArrayList();
	private ArrayList stories = new ArrayList();
	private ArrayList shelters = new ArrayList();

	public void addGift(Gift gift) {
		
		Gift giftCopy = copyGift(gift);
		gifts.add(giftCopy);

		Story storyCopy = getStory(giftCopy.getStory());
		storyCopy.addGift(giftCopy);
		
		Shelter shelterCopy = getShelter(storyCopy.getShelter());
		shelterCopy.addStory(storyCopy);
		
	}

	private Gift copyGift(Gift gift) {
		Gift copy = new Gift();
		copy.setDescription(gift.getDescription());
		copy.setDonor(gift.getDonor());
		copy.setId(gift.getId());
		copy.setStory(gift.getStory());
		return copy;
	}

	public void removeGift(Gift gift) {
		if(gifts.remove(gift)){
			Story story = gift.getStory();
			story.removeGift(gift);
			if(story.getGiftCount() == 0) {
				stories.remove(story);
				Shelter shelter = story.getShelter();
				shelter.removeStory(story);
				if(shelter.getStories().size() == 0){
					shelters.remove(shelter);
				}
			}
		}


	}

	public int getNumberOfGifts() {
		return gifts.size();
	}

	public ArrayList getGifts() {
		return gifts;
	}

	public ArrayList getShelters() {
		return shelters;
	}

	private Story getStory(Story story) {
		int index = stories.indexOf(story);
		if(index >= 0){
			Story foundStory = (Story) stories.get(index);
			return foundStory;
		} else {
			Story newStory = copyStory(story);
			stories.add(newStory);
			return newStory;
		}
	}
	
	private Story copyStory(Story story) {
		Story copy = new Story();
		copy.setAssignedId(story.getAssignedId());
		copy.setFirstName(story.getFirstName());
		copy.setGender(story.getGender());
		copy.setId(story.getId());
		copy.setLastInitial(story.getLastInitial());
		copy.setStory(story.getStory());
		copy.setShelter(story.getShelter());
		return copy;
	}

	private Shelter getShelter(Shelter shelter) {
		int index = shelters.indexOf(shelter);
		if(index >= 0){
			Shelter foundShelter = (Shelter) shelters.get(index);
			return foundShelter;
		} else {
			Shelter newShelter = copyShelter(shelter);
			shelters.add(newShelter);
			return newShelter;
		}
	}

	private Shelter copyShelter(Shelter shelter) {
		Shelter copy = new Shelter();
		copy.setAdditionalDetails(shelter.getAdditionalDetails());
		copy.setAddress(shelter.getAddress());
		copy.setCityId(shelter.getCityId());
		copy.setId(shelter.getId());
		copy.setIdFormat(shelter.getIdFormat());
		copy.setName(shelter.getName());
		copy.setPhone(shelter.getPhone());
		copy.setWebsite(shelter.getWebsite());
		copy.setWhatTheyDo(shelter.getWhatTheyDo());
		copy.setWhatTheyNeed(shelter.getWhatTheyNeed());
		return copy;
	}

}
